/*
 * FilePath     : \src\components\univerSheet\plugin\customMenuPlugin.ts
 * Author       : 苏军志
 * Date         : 2024-10-04 14:10
 * LastEditors  : 苏军志
 * LastEditTime : 2025-03-11 15:46
 * Description  : 自定义菜
 * CodeIterationRecord:
 */

import {
  type Dependency,
  type ICommand,
  Plugin,
  UniverInstanceType,
  Disposable,
  ICommandService,
  Inject,
  Injector
} from "@univerjs/presets";
import {
  ComponentManager,
  ContextMenuGroup,
  ContextMenuPosition,
  IMenuManagerService,
  RibbonStartGroup
} from "@univerjs/presets/preset-sheets-core";
let customCommands: ICommand[] = [];
let customMenus: Record<string, Record<string, any>> = {};
let customMenuIcons: Record<string, Function> = {};
class CustomMenuController extends Disposable {
  constructor(
    @Inject(Injector) private readonly injector: Injector,
    @ICommandService private readonly commandService: ICommandService,
    @IMenuManagerService private readonly menuMangerService: IMenuManagerService,
    @Inject(ComponentManager) private readonly componentManager: ComponentManager
  ) {
    super();
    this.registerComponents();
    this.initCommands();
    this.initMenus();
  }

  private registerComponents(): void {
    Object.keys(customMenuIcons).forEach((menuIconKey) => {
      this.disposeWithMe(this.componentManager.register(menuIconKey, customMenuIcons[menuIconKey], { framework: "vue3" }));
    });
  }

  /**
   * @description: 初始化菜单对应的指令
   */
  private initCommands(): void {
    customCommands.forEach((command) => {
      if (!this.commandService.hasCommand(command.id)) {
        this.disposeWithMe(this.commandService.registerCommand(command));
      }
    });
  }

  /**
   * @description: 初始化菜单
   */
  private initMenus(): void {
    this.menuMangerService.mergeMenu({
      [RibbonStartGroup.FORMAT]: {
        ...customMenus
      },
      [ContextMenuPosition.MAIN_AREA]: {
        [ContextMenuGroup.LAYOUT]: {
          ...customMenus
        }
      }
    });
  }
}
// 自定义插件名称
const SHEET_CUSTOM_MENU_PLUGIN = "SHEET_CUSTOM_MENU_PLUGIN";
/**
 * @description: 自定义插件渲染
 */
export class CustomMenuPlugin extends Plugin {
  static override type = UniverInstanceType.UNIVER_SHEET;
  static override pluginName = SHEET_CUSTOM_MENU_PLUGIN;

  constructor(
    config: any,
    @Inject(Injector) protected readonly _injector: Injector // commands: Record<string, ICommand[]>,
  ) {
    super();
    const { commands, menus, menuIcons } = config;
    customCommands = commands;
    customMenus = menus;
    customMenuIcons = menuIcons;
  }
  /**
   * @description: 重写
   * @param injector
   * @return
   */
  override onStarting(): void {
    ([[CustomMenuController]] as Dependency[]).forEach((d) => this._injector.add(d));
  }

  onReady(): void {
    this._injector.get(CustomMenuController);
  }
}
